package com.rongshu.view.userInfo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.rongshu.R;
import com.rongshu.eventbus.NumberOfArticleStates;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.activity.SelectFloderActivity;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.submitArticle.activity.SubmitArticleActivity;
import com.rongshu.view.submitArticle.bean.SavaDraftBody;
import com.rongshu.view.userInfo.activity.PreviewActivity;
import com.rongshu.view.userInfo.adapter.CollectedArticleAdapter;
import com.rongshu.view.userInfo.entity.Article;
import com.rongshu.view.userInfo.entity.CollectedArticle;
import com.rongshu.view.userInfo.iview.CollectedArticleView;
import com.rongshu.view.userInfo.listener.OnCorpusItemClickListener;
import com.rongshu.view.userInfo.presenter.CollectedArticlePresenter;
import com.rongshu.widget.BanyanDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

public class CollectedArticleFragment extends BaseFragment<CollectedArticlePresenter> implements CollectedArticleView, OnCorpusItemClickListener {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;

    //manager
    private LinearLayoutManager manager = null;
    //list
    private List<CollectedArticle.ResponseBean> beanList = null;
    //adapter
    private CollectedArticleAdapter adapter = null;
    //dialog
    private BanyanDialog dialog = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //refresh,load
    private boolean isrefresh = true;
    //筛选类型 type
    private int type = 0;
    //intent
    private Intent intent = null;
    //bundle
    private Bundle bundle = null;
    //文集id
    private int serialize = 0;
    //文章id
    private int contribute_id = 0;
    //文集name
    private String selectFloderName = null;
    //position
    private int mPosition = 0;
    //request
    private final int EDIT_REQUEST = 0x01;
    private final int SELECT_FLODER = 0x02;//选择文集


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_collected_article_view;
    }

    @Override
    protected void initViews() {
        //set presenter
        setPresenter(new CollectedArticlePresenter(getActivity()), this);
        //intent
        bundle = getArguments();
        if (bundle != null) {
            serialize = bundle.getInt(Constant.INTENT_MESSAGE, 0);
            type = bundle.getInt(Constant.INTENT_TYPE, 0);
        }
        //layoutmanager
        manager = new LinearLayoutManager(getActivity());
        //list
        beanList = new ArrayList<>();
        //adapter
        adapter = new CollectedArticleAdapter(getActivity());
        adapter.setOnCorpusItemClickListener(this);
        adapter.setCollectedArticles(beanList);
        //recyclerview
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        recyclerview.setLayoutManager(manager);
        recyclerview.setAdapter(adapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                isrefresh = true;
                pageIndex = 1;
                refreshlayout.resetNoMoreData();
                getMyArticle(serialize);
                refreshlayout.finishRefresh(5000, true);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isrefresh = false;
                pageIndex++;
                getMyArticle(serialize);
                refreshlayout.finishLoadmore(5000, true);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * APP获取文集下的文章列表
     */
    private void getMyArticle(int serialize_id) {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(getContext());
            return;
        }
        if (serialize_id == 0) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("serialize_id", serialize_id);
        map.put("type", type);//(0全部 1已发布 2审核中 3草稿)
        map.put("page", pageIndex);
        map.put("pagesize", pageSize);
        presenter.getMyArticle(user_id, serialize_id, type, pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * APP删除文章
     */
    private void getDeleteContribute(int contribute_id) {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(getContext());
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", contribute_id);
        presenter.getDeleteContribute(user_id, contribute_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * APP移动文章
     */
    private void getMoveContribute(int contribute_id, int serial_id) {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(getContext());
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", contribute_id);
        map.put("serial_id", serial_id);
        presenter.getMoveContribute(user_id, contribute_id, serial_id, Common.encryptionSign(map));
        map.clear();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EDIT_REQUEST://编辑页面返回
                    refreshLayout.autoRefresh();
                    break;
                case SELECT_FLODER://移动选择文集返回
                    if (data != null) {
                        Article.ResponseBean bean = (Article.ResponseBean) data.getSerializableExtra(Constant.INTENT_DATA);
                        int articleFloderId = bean.getId();
                        selectFloderName = bean.getTitle();
                        getMoveContribute(contribute_id, articleFloderId);
                    }
                    break;
            }
        }
    }

    /**
     * 提示
     */
    public void showCollectedDialog(final int position) {
        int contribute_id = adapter.getCollectedArticles().get(position).getContribute_id();
        int is_check = adapter.getCollectedArticles().get(position).getIs_check();
        //dialog
        BanyanDialog.Builder builder = new BanyanDialog.Builder(getActivity());
        builder.setTitle(is_check == 1 || is_check == 2 ? "审核状态无法删除" : "删除文章");
        builder.setContent(is_check == 1 || is_check == 2 ? "如需删除\n请联系榕书编辑" : "文章将移至回收站 可保存60天");
        builder.setLeft(is_check == 1 || is_check == 2 ? "联系方式：RS@rongshu.com" : getString(R.string.cancle));
        if (is_check == 3 || is_check == 4) {
            builder.setRight(getString(R.string.alert_confirm));
        }
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                getDeleteContribute(contribute_id);
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    /**
     * item click
     */
    @Override
    public void onClick(int is_check, int draftId, String title, String content, String topImg) {
        if (is_check == 3 || is_check == 4) {
            enterIntoSubmit(draftId, title, content, topImg);
        } else if (is_check == 1) {
            enterInfoArticleDetails(draftId);
        } else if (is_check == 2) {
            intent = new Intent(getContext(), PreviewActivity.class);
            intent.putExtra(Constant.INTENT_TITLE, title);
            intent.putExtra(Constant.INTENT_DATA, topImg);
            intent.putExtra(Constant.INTENT_MESSAGE, draftId);
            startActivity(intent);
        }
    }

    /**
     * 移动 click
     *
     * @param contribute_id
     */
    @Override
    public void onMoveClick(int position, int contribute_id) {
        this.mPosition = position;
        this.contribute_id = contribute_id;
        intent = new Intent(getActivity(), SelectFloderActivity.class);
        intent.putExtra(Constant.INTENT_TYPE, SubmitArticleActivity.class.getSimpleName());
        startActivityForResult(intent, SELECT_FLODER);
    }

    /**
     * 编辑 click
     */
    @Override
    public void onEditClick(int draftId, String title, String content, String topImg) {
        enterIntoSubmit(draftId, title, content, topImg);
    }

    /**
     * 进入编辑界面
     */
    private void enterIntoSubmit(int draftId, String title, String content, String topImg) {
        Intent intent = new Intent(getActivity(), SubmitArticleActivity.class);
        //body
        SavaDraftBody savaDraftBody = new SavaDraftBody();
        savaDraftBody.setTitle(title);
        savaDraftBody.setContent(content);
        savaDraftBody.setTopImg(topImg);
        intent.putExtra(Constant.DRAFT_ID, draftId);
        intent.putExtra(Constant.FOLDER_ID, serialize);
        intent.putExtra(Constant.DRAFT_DOBY, savaDraftBody);
        this.startActivityForResult(intent, EDIT_REQUEST);
    }

    /**
     * 进入文章详情页面
     */
    private void enterInfoArticleDetails(int contribute_id) {
        //发送的实体类
        ArticleDetaisRequest request = new ArticleDetaisRequest();
        request.setContribute_id(contribute_id);
        request.setType(6);
        request.setTopic_id(0);
        intent = new Intent(getActivity(), SingleArticleDetailsActivity.class);
        intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, request);
        startActivity(intent);
    }

    /**
     * 删除 click
     */

    @Override
    public void onItemDeleteClick(int position) {
        this.mPosition = position;
        showCollectedDialog(position);
    }

    /**
     * APP获取文集下的文章列表回调
     */
    @Override
    public void onCollectedArticleList(CollectedArticle collectedArticle) {
        List<CollectedArticle.ResponseBean> beans = collectedArticle.getResponse();
        if (adapter != null) {
            if (isrefresh) {
                refreshLayout.finishRefresh();
                refreshLayout.setVisibility(beans == null || beans.isEmpty() ? View.GONE : View.VISIBLE);
                layout_empty.setVisibility(beans == null || beans.isEmpty() ? View.VISIBLE : View.GONE);
                beanList.clear();
                beanList.addAll(beans);
                adapter.notifyDataSetChanged();
            } else {
                if (beans == null || beans.isEmpty()) {
                    refreshLayout.finishLoadmoreWithNoMoreData();
                } else {
                    refreshLayout.finishLoadmore();
                    beanList.addAll(beans);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * APP删除文章
     *
     * @param bean
     */
    @Override
    public void onDeleteContribute(INetBean bean) {
        this.beanList.remove(mPosition);
        adapter.notifyItemRemoved(mPosition);
        adapter.notifyItemRangeChanged(mPosition, adapter.getItemCount() - mPosition);
        EventBus.getDefault().post(new NumberOfArticleStates());
    }

    /**
     * APP移动文章
     *
     * @param bean
     */
    @Override
    public void onMoveContribute(INetBean bean) {
        if (bean.getErrCode() == 0) {
            toast("成功移动到" + selectFloderName);
            this.beanList.remove(mPosition);
            adapter.notifyItemRemoved(mPosition);
            adapter.notifyItemRangeChanged(mPosition, adapter.getItemCount() - mPosition);
            EventBus.getDefault().post(new NumberOfArticleStates());
        } else {
            toast(bean.getErrMsg());
        }
    }
}
